import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:basic_utils/basic_utils.dart';
import 'package:lib_core/const/net_cst.dart';
import 'package:pointycastle/asymmetric/pkcs1.dart';
import 'package:pointycastle/asymmetric/rsa.dart';
import 'package:pointycastle/export.dart';

/// 加密工具类
class EncryptUtils {
  static RSAPublicKey _parsePublicKey(String base64) {
    var pem = '-----BEGIN RSA PUBLIC KEY-----\n$base64\n-----END RSA PUBLIC KEY-----';
    return CryptoUtils.rsaPublicKeyFromPem(pem);
  }


  static String encrypt(String data) {
    final String key;
    if (NetCst().hostUrl.startsWith('https://lcapi.midea.com/') || NetCst().hostUrl.startsWith('https://anapi.annto.com/')) {
      key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6kQe8EDH7Fs7KJT02htN30jAH" + "Gzp9qwQFfa9KOsUjzT68Cx6Gac5xxdQ5ILy4b8aS+VrqYcsKRerPZpzxAU9twCR3" + "mRLyWX/2jcJk5kLjxrbLIkNwLveO05sirRNGFTIZIf2tIfGOAZwnlo/cPogmkprm" + "QYTiHzXOA67lXFZaVQIDAQAB";
    } else {
      key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdUn+Y0OTj+i4KVMzcnk2z3fpfrdtHPcsHQgbdKOjvi2B/jFYQAikwUjgDPI" + "zf9BDVCckgxc5LcD5doe7fYYlgxYeoU/KzdEQbKO9DcPPfp2gilwowD48kQf1N2b9t57QKSjTPMMiW2tROsr83JqkS2F" + "waJHEZ7UZJTx57VfcOlQIDAQAB";
    }
    final publicKey = _parsePublicKey(key);
    final cipher = PKCS1Encoding(RSAEngine());
    cipher.init(true, PublicKeyParameter<RSAPublicKey>(publicKey));
    Uint8List output = cipher.process(Uint8List.fromList(utf8.encode(data)));
    var base64EncodedText = base64Encode(output);
    return base64EncodedText;
  }
}
